package cn.rocket.util;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URISyntaxException;

import org.springframework.stereotype.Component;
@Component("fileUtil")
public class FileUtil {
	/** 
     * 根据byte数组，生成文件 
     */ 
	public void getFile(byte[] bfile, String filePath,String fileName) {  
		System.out.println("视频保存路径："+filePath+fileName);
        BufferedOutputStream bos = null;  
        FileOutputStream fos = null;  
        File file = null;  
        File filetemp = null;
        try {  
            File dir = new File(filePath);  
            if(!dir.exists()){//判断文件目录是否存在  
                dir.mkdirs();  
            }
            
//            filetemp = new File("D:/"+fileName);
//            fos = new FileOutputStream(filetemp);
//            bos = new BufferedOutputStream(fos);  
//            bos.write(bfile);
            
            file = new File(filePath+fileName);
            if (!file.exists()){
            	if (file.createNewFile()){
            		System.out.println("文件创建成功！");
            	}else{
            		System.out.println("文件创建失败！");
            	}
            	
            }else{
            	System.out.println("文件存在！");
            }
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);  
            bos.write(bfile);
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            if (bos != null) {  
                try {  
                    bos.close();  
                } catch (IOException e1) {  
                    e1.printStackTrace();  
                }  
            }  
            if (fos != null) {  
                try {  
                    fos.close();  
                } catch (IOException e1) {  
                    e1.printStackTrace();  
                }  
            }  
        }  
    }  
	

	public static byte[] getBytes(String filePath){  
        byte[] buffer = null;  
        try {  
            File file = new File(filePath);  
            FileInputStream fis = new FileInputStream(file);  
            ByteArrayOutputStream bos = new ByteArrayOutputStream(10000);  
            byte[] b = new byte[10000];
            int n;  
            while ((n = fis.read(b)) != -1) {  
                bos.write(b, 0, n);  
            }  
            fis.close();  
            bos.close();  
            buffer = bos.toByteArray();  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
        } catch (IOException e) {  
            e.printStackTrace();  
        }  
        return buffer;  
    }
	
	public static void main(String[] args) throws URISyntaxException, IOException{
		System.out.println(FileUtil.class.getClassLoader().getResource("").getPath());
	}
}
